package com.beisita.base.handler;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.beisita.base.enums.ResultCodeEnum;
import com.beisita.base.result.ErrorResult;
import com.beisita.base.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/*@ControllerAdvice注解加上basePackages,不加的话，
将对整个系统的Controller做扩展功能， 它会对某些特殊功能产生冲突，
例如 不加的话，在使用swagger时会出现空白页异常。*/
@RestControllerAdvice(basePackages = "com.beisita.web.controller")
@Slf4j
@Order(20)
public class ResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * 是否支持advice功能
     * treu=支持，false=不支持
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //假设返回的是fastjson处理的才进入此advice处理，这里可自行根据业务情况配置
        return FastJsonHttpMessageConverter.class.equals(converterType) || !returnType.getMethod().getReturnType().isAssignableFrom(Void.TYPE);
    }

    /**
     * 处理response的具体业务方法
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (log.isDebugEnabled()) {
            log.debug("advice by ResponseHandler,beforeBodyWrite");
        }
        if (o instanceof ErrorResult) {
            ErrorResult errorResult = (ErrorResult) o;
            return Result.fail(ResultCodeEnum.WEB_500, errorResult.getMessage());
        }
        return Result.success(o);
    }
}
